<?php
namespace app\forum\model;
use app\base\model\BaseModel;
/**
 * 用户操作
 */
class UserModel extends BaseModel {

    //完成
    protected $_auto = array (
        array('username','htmlspecialchars',1,'function'),  //用户名
        array('email','htmlspecialchars',3,'function'),  //邮箱
        array('password','md5',1,'function'),  //新增时密码
        array('password','',2,'ignore'),  //编辑时密码
        array('status',1,1,'string'),  //状态
        array('status','intval',3,'function'),  //状态
        array('reg_time','time',1,'function'),  //注册时间
        array('integral',0,1,'string'),  //注册积分
        array('group_id',1,1,'string'),  //用户组
     );
    //验证
    protected $_validate = array(
        array('username','/^(?!_|\s\')[A-Za-z0-9_\x80-\xff\s\']+$/', '用户名称只能为中文、英文、数字、下划线', 1 ,'regex',1),
        array('username', '', '已存在相同的用户名', 1, 'unique',1),
        array('email','email', '邮箱地址输入不正确', 1 ,'regex',1),
        array('password', '4,250', '请输入最少4位密码', 1, 'length',1),
    );

    /**
     * 获取列表
     * @return array 列表
     */
    public function loadList($where = array(), $limit = 0){
        $data = $this->table('user as A')
                ->join('{pre}user_group as B ON A.group_id = B.group_id')
                ->field('A.*,B.name as group_name')
                ->where($where)
                ->limit($limit)
                ->order('A.user_id desc')
                ->select();
        return $data;
    }

    /**
     * 获取数量
     * @return int 数量
     */
    public function countList($where = array()){

        return $this->table('user as A')
                ->join('{pre}user_group as B ON A.group_id = B.group_id')
                ->where($where)
                ->count();
    }

    /**
     * 获取信息
     * @param int $userId ID
     * @return array 信息
     */
    public function getInfo($userId)
    {
        $map = array();
        $map['user_id'] = $userId;
        return $this->getWhereInfo($map);
    }

    /**
     * 获取头像
     */
    public function avatar($userId){
        $avatar = 'upload/avatar/'.$userId.'.jpg';
        if(is_file(ROOT_PATH . $avatar)){
            return $avatar;
        }else{
            return ROOT_URL . '/' . THEME_NAME . '/' . TPL_NAME . '/default.jpg';
        }
    }

    /**
     * 获取信息
     * @param array $where 条件
     * @return array 信息
     */
    public function getWhereInfo($where)
    {        

        return $this->table('user as A')
                ->join('{pre}user_group as B ON A.group_id = B.group_id')
                ->field('A.*,B.status as group_status,B.name as group_name,B.admin,B.special,B.integral_limit')
                ->where($where)
                ->find();
    }

    /**
     * 更新信息
     * @param string $type 更新类型
     * @param string $field 写入字段
     * @return bool 更新状态
     */
    public function saveData($type = 'add',$field=''){
        $data = $this->create();
        if(!$data){
            return false;
        }
        if($type == 'add'){
            return $this->into($field)->add();
        }
        if($type == 'edit'){
            if(empty($data['user_id'])){
                return false;
            }
            if (!empty($data['password'])){ //密码非空，处理密码加密
                $data['password'] = md5($data['password']);
            }
            $status = $this->into($field)->save($data);
            if($status === false){
                return false;
            }
            return true;
        }
        return false;
    }

    /**
     * 保存信息
     * @return bool 更新状态
     */
    public function saveInfo($data)
    {
        $validate = array(
            array('email','email', '邮箱地址输入不正确', 1 ,'regex',3),
            array('password', '4,250', '请输入最少4位密码', 2, 'length',3),
            array('password2', 'password', '重复密码输入不正确', 2, 'confirm',3),
            );
        $auto = array(
            array('password','',2,'ignore'),  //编辑时密码
            );
        $data = target('User')->auto($auto)->validate($validate)->create();
        if(!$data){
            return false;
        }
        if(empty($data['user_id'])){
            return false;
        }
        if (!empty($data['password'])){ //密码非空，处理密码加密
            $data['password'] = md5($data['password']);
        }
        $status = $this->into('email,password')->save($data);
        if($status === false){
            return false;
        }
        return true;
    }

    /**
     * 删除信息
     * @param int $userId ID
     * @return bool 删除状态
     */
    public function delData($userId)
    {
        $map = array();
        $map['user_id'] = $userId;
        return $this->where($map)->delete();
    }

    /**
     * 登录用户
     * @param int $userId ID
     * @return bool 登录状态
     */
    public function setLogin($userId)
    {
        // 更新登录信息
        $data = array(
            'user_id' => $userId,
            'last_login_time' => NOW_TIME,
            'last_login_ip' => \framework\ext\Util::getIp(),
        );
        $this->save($data);
        //设置cookie
        cookie('user_id', $userId);
        $sign = array(
            'user_id' => $userId,
            'key' => config('SAFE_KEY'),
        );
        cookie('user_sign', data_auth_sign($sign));
        return true;
    }

    /**
     * 注销当前用户
     * @return void
     */
    public function logout(){
        cookie('user_id', null, -1);
        cookie('user_sign', null, -1);
    }

}
